const { db } = require('../config/database');

class HealthReport {
  // 添加健康报告
  static create(reportData) {
    const { user_id, title, report_date, description, file_path } = reportData;
    
    return new Promise((resolve, reject) => {
      db.run(
        'INSERT INTO health_reports (user_id, title, report_date, description, file_path) VALUES (?, ?, ?, ?, ?)',
        [user_id, title, report_date, description, file_path],
        function(err) {
          if (err) {
            reject(err);
          } else {
            resolve({
              id: this.lastID,
              user_id,
              title,
              report_date,
              description,
              file_path,
              created_at: new Date().toISOString()
            });
          }
        }
      );
    });
  }

  // 获取用户所有健康报告
  static findAllByUserId(userId) {
    return new Promise((resolve, reject) => {
      db.all('SELECT * FROM health_reports WHERE user_id = ? ORDER BY created_at DESC', [userId], (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }

  // 根据ID获取健康报告
  static findById(id) {
    return new Promise((resolve, reject) => {
      db.get('SELECT * FROM health_reports WHERE id = ?', [id], (err, row) => {
        if (err) {
          reject(err);
        } else {
          resolve(row);
        }
      });
    });
  }

  // 更新健康报告
  static update(id, reportData) {
    const { title, report_date, description } = reportData;
    
    return new Promise((resolve, reject) => {
      db.run(
        'UPDATE health_reports SET title = ?, report_date = ?, description = ? WHERE id = ?',
        [title, report_date, description, id],
        function(err) {
          if (err) {
            reject(err);
          } else {
            resolve(this.changes > 0);
          }
        }
      );
    });
  }

  // 删除健康报告
  static delete(id) {
    return new Promise((resolve, reject) => {
      db.run('DELETE FROM health_reports WHERE id = ?', [id], function(err) {
        if (err) {
          reject(err);
        } else {
          resolve(this.changes > 0);
        }
      });
    });
  }
}

module.exports = HealthReport; 